



/**
 
 @IBAction func askForDocument(_ sender: Any) {
 
     let types = [
        "dyn.ah62d4rv4ge80k8dg",
     ]
     
     openForDocument(sender, types: types)
 }
 
 func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    xx_documentPickerWasCancelled(controller)
 }
 
 func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    xx_documentPicker(controller, didPickDocumentsAt: urls)
 }
 
 func readDocumentProcessImportedFileAt(fileURL: URL) {
    log.e(fileURL.absoluteURL.description)
 }
 
 
 */

fileprivate typealias log = XXLoger

public protocol ReadDocumentProtocol:UIDocumentPickerDelegate, UINavigationControllerDelegate {
    func openForDocument(_ sender:Any,types:[String])
    func readDocumentProcessImportedFileAt(fileURL: URL,types:[String]?)
}


public extension ReadDocumentProtocol where Self:UIViewController {
    
    func openForDocument(_ sender:Any,types:[String]){
        let iOSPickerUI = UIDocumentPickerViewController(documentTypes: types, in: .import)
        iOSPickerUI.delegate = self
        iOSPickerUI.modalPresentationStyle = .formSheet
        iOSPickerUI.xx.tag = types
        if let popoverPresentationController = iOSPickerUI.popoverPresentationController {
            popoverPresentationController.sourceView = sender as? UIView
        }
        self.present(iOSPickerUI, animated: true, completion: nil)
    }
    
    func xx_documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        dismiss(animated: true, completion: nil)
    }
    
    func xx_documentPicker(_ iOSPickerUI: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        if iOSPickerUI.allowsMultipleSelection {
            log.d("WARNING: controller allows multiple file selection, but coordinate-read code here assumes only one file chosen")
            // If this is intentional, you need to modify the code below to do coordinator.coordinate
            // on MULTIPLE items, not just the first one
            if urls.count > 0 { print("Ignoring all but the first chosen file") }
        }
        
        let firstFileURL = urls[0]
        let isSecuredURL = (firstFileURL.startAccessingSecurityScopedResource() == true)
        
        log.d("UIDocumentPickerViewController 获取到url = \(firstFileURL)")
        
        // Status monitoring for the coordinate block's outcome
        var blockSuccess = false
        var outputFileURL: URL? = nil
        
        // Execute (synchronously, inline) a block of code that will copy the chosen file
        // using iOS-coordinated read to cooperate on access to a file we do not own:
        let coordinator = NSFileCoordinator()
        let error: NSErrorPointer = .none
        coordinator.coordinate(readingItemAt: firstFileURL, options: [], error: error) { (externalFileURL) -> Void in
            
            // WARNING: use 'externalFileURL in this block, NOT 'firstFileURL' even though they are usually the same.
            // They can be different depending on coordinator .options [] specified!
            
            // Create file URL to temp copy of file we will create:
            var tempURL = URL(fileURLWithPath: NSTemporaryDirectory())
            tempURL.appendPathComponent(externalFileURL.lastPathComponent)
            log.d("尝试将文件复制到临时文件夹 = \(tempURL)")
            
            // Attempt copy
            do {
                // If file with same name exists remove it (replace file with new one)
                if FileManager.default.fileExists(atPath: tempURL.path) {
                    print("删除现有文件: \(tempURL.path)")
                    try FileManager.default.removeItem(atPath: tempURL.path)
                }
                
                // Move file from app_id-Inbox to tmp/filename
                log.d("尝试将文件移动到: \(tempURL.path)")
                try FileManager.default.moveItem(atPath: externalFileURL.path, toPath: tempURL.path)
                
                blockSuccess = true
                outputFileURL = tempURL
            }
            catch {
                log.d("文件操作错误:" + error.localizedDescription)
                blockSuccess = false
            }
            
        }
//        navigationController?.dismiss(animated: true, completion: nil)
        
        if error != nil {
            log.d("NSFileCoordinator() generated error while preparing, and block was never executed")
            return
        }
        if !blockSuccess {
            log.d("Block executed but an error was encountered while performing file operations")
            return
        }
        
        log.d("输出URL : \(String(describing: outputFileURL))")
        
        if (isSecuredURL) {
            firstFileURL.stopAccessingSecurityScopedResource()
        }
//        iOSPickerUI.type
        if let out = outputFileURL {
            readDocumentProcessImportedFileAt(fileURL: out,types: iOSPickerUI.xx.tag as? [String])
        }
        
    }
    
}
